<?php
class PC4_View extends Zend_View {
	
	public $pastasView;
    /**
     * Finds a view script from the available directories.
     *
     * @param string $name The base name of the script.
     * @return void
     */
    protected function _script($name)
    {
    	$achou = false;

		$pasta = $name;
		$ultimaBarra = strpos($pasta, '/');
		if($ultimaBarra !== false){
			$acao = substr($pasta, $ultimaBarra + 1);
			$pasta = substr($pasta, 0, $ultimaBarra);
			if (!in_array($pasta, $this->getPastasView())) {
				$this->prependPastaView($pasta);
			}
		}
		else {
			$acao = $pasta;
		}
		
		// procura view scripts na hierarquia de pastas configurada
		$pastas = $this->getPastasView();
		foreach ($pastas as $pasta) {
			$viewScript = (empty($pasta)) ? $acao : $pasta . '/' . $acao;
			$paths = $this->getScriptPaths();
			foreach ($paths as $path) {
				$path .= $viewScript;

				$this->debug['viewscripts'][] = $path;
			
				if (file_exists($path)) {
					$achou = true;
					break 2;
				}  
			}
		}

		if ($achou) {
			$this->debug['viewscripts']['escolhido'] = $viewScript;
		}

    	$viewScript = parent::_script($viewScript);

    	return $viewScript;
    }

	/**
	 * Adiciona uma pasta na hierarquia de pastas onde será procurada a view
	 * @param string $pasta
	 * @param int $i A posição onde a pasta será adicionada
	 */
	public function addPastasView($pastas, $i = 0) {
		foreach ((array) $pastas as $pasta) {
			$this->addPastaView($pasta, $i);
		}
	}
	public function addPastaView($pasta, $i = 0) {
		$this->initPastaView();
		array_splice($this->pastasView, $i, 0, $pasta);
	}	
	public function prependPastaView($pasta) {
		$this->initPastaView();
		$this->addPastaView($pasta);
	}
	public function appendPastaView($pasta) {
		$this->initPastaView();
		array_push($this->pastasView, $pasta);
	}
	public function getPastasView() {
		$this->initPastaView();
		return $this->pastasView;
	}
	function initPastaView() {
		if ($this->pastasView == null) {
			$this->pastasView = array('');
		}
	}
	
}